package com.ruoyi.sgsc.controller;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.sgsc.domain.UserResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.sgsc.domain.users;
import com.ruoyi.sgsc.service.IusersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


/**
 * 用户Controller
 * 
 * @author wy
 * @date 2024-09-29
 */
@Anonymous
@RestController
@RequestMapping("/sgsc/users")
public class usersController extends BaseController
{
    @Autowired
    private IusersService usersService;

    /**
     * 用户登录
     * @param userInfo
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> userInfo) {
        try {
            String userName = userInfo.get("userName");
            String password = userInfo.get("password");
            users user = usersService.login(userName, password);

            if (user == null) {
                // 提供更具体的错误信息
                return ResponseEntity.badRequest().body("用户名或密码不正确E001");
            } else {
                // 创建用户信息响应对象
                UserResponse userResponse = new UserResponse(
                        // 省略密码和其他不需要的信息
                        user.getUserId(),
                        user.getUserName(),
                        user.getPhone()
                );

                // 设置登录成功的响应，包括用户信息和状态码
                return ResponseEntity.ok().body(userResponse);
            }
        } catch (Exception e) {
            // 记录异常信息到日志系统
            logger.error("登录过程中发生异常", e);
            // 返回一个通用的错误响应
            return ResponseEntity.internalServerError().body("服务器内部错误E500");
        }
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody users user) {
        if (user == null) {
            return ResponseEntity.badRequest().body("请求体不能为空");
        }
        String userName = user.getUserName();
        String password = user.getPassword();
        String phone = user.getPhone();

        // 参数校验
        if (userName == null || userName.isEmpty() || password == null || password.isEmpty() || phone == null || phone.isEmpty()) {
            return ResponseEntity.badRequest().body("用户名、密码和手机号不能为空");
        }

        // 手机号格式验证
        if (!isValidPhone(phone)) {
            return ResponseEntity.badRequest().body("请输入正确的手机号格式");
        }

        // 注册用户
        int result = usersService.register(user);
        if (result > 0) {
            return ResponseEntity.ok("注册成功");
        } else {
            return ResponseEntity.status(400).body("注册失败");
        }
    }

    private boolean isValidPhone(String phone) {
        // 中国大陆手机号正则表达式，以1开头，第二位是3-9，总共11位数字
        String regex = "^1[3-9]\\d{9}$";
        return phone != null && phone.matches(regex);
    }



    /**
     * 查询用户列表
     */

    @GetMapping("/list")
    public TableDataInfo list(users users)
    {
        startPage();
        List<users> list = usersService.selectusersList(users);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */

    @PostMapping("/export")
    public void export(HttpServletResponse response, users users)
    {
        List<users> list = usersService.selectusersList(users);
        ExcelUtil<users> util = new ExcelUtil<users>(users.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */

    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return success(usersService.selectusersByUserId(userId));
    }



    /**
     * 新增用户
     */

    @PostMapping
    public AjaxResult add(@RequestBody users users)
    {
        return toAjax(usersService.insertusers(users));
    }

    /**
     * 修改用户
     */

    @PutMapping
    public AjaxResult edit(@RequestBody users users)
    {
        return toAjax(usersService.updateusers(users));
    }

    /**
     * 删除用户
     */

	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(usersService.deleteusersByUserIds(userIds));
    }

}
